<template>
  <!--角色管理-->
  <div class="app-container">
    <el-form class="jc_search_wrap" v-model="searchList">
      <label>角色名称</label><el-input v-model="searchList.roleName"></el-input>
      <el-button @click="searchRows"><i class="el-icon-search"></i>查询</el-button>
    </el-form>
    <el-button-group class="jc_btn_wrap jc_btn_left">
      <el-button @click="createRow"><i class="jc_icon el-icon-plus"></i>新增角色</el-button>
      <el-button @click="editRow"><i class=""></i>编辑</el-button>
      <el-button @click="deleteRow"><i class=""></i>删除</el-button>
    </el-button-group>
    <el-table :height="tableHeight"  :data="list" v-loading.body="listLoading" element-loading-text="拼命加载中" border fit highlight-current-row class="jc_table_wrap"  @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="80px">
      </el-table-column>
      <!--<el-table-column label='id' v-if="false">
        <template scope="scope">
          {{scope.row.id}}
        </template>
      </el-table-column>-->
      <el-table-column label='角色'>
        <template scope="scope">
          {{scope.row.roleName}}
        </template>
      </el-table-column>
      <el-table-column label='描述'>
        <template scope="scope">
          {{scope.row.remark}}
        </template>
      </el-table-column>
      <el-table-column label='创建时间'>
        <template scope="scope">
          {{scope.row.createTime}}
        </template>
      </el-table-column>
    </el-table>
    <!--<el-pagination layout="prev, pager, next" :total="total" @current-change="changePage" :page-size="10" :current-page="currentPage"/>-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="changePage"
      :current-page="currentPage"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <!--新建-->
    <el-dialog title="新建角色" :visible.sync="create_visible" class="jc_dialog_wrap">
      <el-form :model="form_create" label-width="120px">
        <el-form-item label="角色名">
          <el-input v-model="form_create.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="form_create.remark"></el-input>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-tree style="width: 450px" :data="menuData" leafOnly show-checkbox node-key="menuId" :props="defaultProps" ref="treeMenuCreate" :check-strictly="true">
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCreateForm">确定</el-button>
        <el-button @click="create_visible=false">取消</el-button>
      </div>
    </el-dialog>
    <!--编辑-->
    <el-dialog title="编辑角色" :visible.sync="edit_visible" class="jc_dialog_wrap">
      <el-form :model="form_edit" label-width="120px">
        <el-form-item label="角色名">
          <el-input v-model="form_edit.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="form_edit.remark"></el-input>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-tree style="width: 450px" :data="menuData" show-checkbox node-key="menuId" :props="defaultProps" ref="treeMenu" :default-checked-keys="editMenuTree" :default-expanded-keys="editMenuTree" :check-strictly="true">
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitEditForm">确定</el-button>
        <el-button @click="edit_visible=false">取消</el-button>
      </div>
    </el-dialog>
    <!--详情-->
    <el-dialog title="角色详情" :visible.sync="detail_visible" class="jc_dialog_wrap">
      <el-form :model="form_detail" label-width="120px">
        <el-form-item label="角色名">
          <el-input v-model="form_detail.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-input v-model="form_detail.createTime" disabled></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detail_visible=false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

  import * as Role from "../../api/systemApi/role";
  import * as Menu from "../../api/systemApi/menu";

  export default {
    components: {

    },
    data() {
      return {
        searchList: {
          pageSize: '',
        },
        list: null,
        total: 0,
        currentPage: 1,
        create_visible: false,
        detail_visible: false,
        edit_visible: false,
        form_create: {},
        form_detail: {},
        form_edit: {},
        multipleSelection: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        menuData: [],
        editMenuTree: [],
        pageSize: 10,
        currentPage: 1,
      }

    },
    created() {
      this.fetchData();
      this.getMenuTree();
    },
    methods: {
      fetchData(p) {
        this.listLoading = true;
        this.searchList.pageNum = this.currentPage = p;
        this.searchList.pageSize = this.pageSize;
        Role.getRoleList(this.searchList).then(data => {
          this.list = data.rows;
          this.total = parseInt(data.total);
          this.listLoading = false;
        })

      },
      searchRows() {
        this.fetchData()
      },
      emptyInputs() {
        this.searchList = {};
        this.fetchData()
      },
      createRow() {
        this.create_visible = true;
        this.form_create = {}
        if(this.$refs.treeMenuCreate) { //只有第二次打开dialog才会加载好树形结构
          console.log('ok1');
          this.$refs.treeMenuCreate.setCheckedNodes([]);//清空已选的
        }
      },
      submitCreateForm() {

        var keys = this.$refs.treeMenuCreate.getCheckedKeys();
        console.log('keys',keys);
        this.form_create.menuId = keys.join(',');
        console.log('this.form_create',this.form_create);
        Role.createRole(this.form_create).then(data => {
          this.create_visible = false;
          this.fetchData();
        })
      },
      editRow() {

        if(this.$refs.treeMenu) { //只有第二次打开dialog才会加载好树形结构
          console.log('ok1');
          this.$refs.treeMenu.setCheckedNodes([]);//清空已选的
          this.editMenuTree = []; //清空展开项
        }
        if(this.multipleSelection.length === 0) {
          alert('请先勾选行');
        }else if(this.multipleSelection.length >= 2) {
          alert('每次最多勾选一行');
        }else if(this.multipleSelection.length === 1) {
          Role.searchRoleRow({roleId: this.multipleSelection[0].roleId}).then(data => {
            this.edit_visible = true;
            //只能把要的数据存下
            this.form_edit.oldRoleName = data.msg.roleName; //修改时要提交旧名字
            this.form_edit.roleName = data.msg.roleName;
            this.form_edit.roleId = data.msg.roleId;
            this.form_edit.remark = data.msg.remark;
            //只有第二次打开dialog才会加载好树形结构
            if( this.$refs.treeMenu) {//第二次打开时 勾选
              console.log('data.msg.menuIds',data.msg.menuIds[0]);
              if(data.msg.menuIds[0] !== null) { //防止没有勾选角色的情况
                this.$refs.treeMenu.setCheckedKeys(data.msg.menuIds);
                this.editMenuTree=data.msg.menuIds; //第二次打开之后 的展开项
              }
            }else {
              this.editMenuTree=data.msg.menuIds; //第一次打开时，勾选
            }
          })
        }
      },
      submitEditForm() {
        var keys = this.$refs.treeMenu.getCheckedKeys();
        console.log('keys',keys);
        this.form_edit.menuId = keys.join(',');
        Role.updateRole(this.form_edit).then(data => {
          this.edit_visible = false;
          this.fetchData(this.currentPage);
        })
      },
      detailRow(row) {
      },
      deleteRow() {
        if(this.multipleSelection.length === 0) {
          alert('请先勾选行');
        }else if(this.multipleSelection.length >= 2) {
          alert('每次最多勾选一行');
        }else if(this.multipleSelection.length === 1){
          this.$confirm('是否删除该条数据?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            Role.delRow({ids:this.multipleSelection[0].roleId}).then(data => {
              this.fetchData(this.currentPage);
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
            })

          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });

        }
      },
      getMenuTree() {
        this.menuData = [];  //先清空数据
        function getTree(data,parentData) {
          var childrenArr = [] //所有非一级父元素的集合
          for(var i=0;i<data.length;i++) {
            var obj = {};
            var objChildrens = {};
            if(data[i].parentId === 0) { //parentId是0,说明是父元素，它的里面可能会有子集
              obj.label=data[i].menuName;
              obj.menuId=data[i].menuId;
              obj.parentId=data[i].parentId;
              obj.children = [];
              parentData.push(obj);
            }else { //找到所有的子集 装在childrenArr
              objChildrens.label=data[i].menuName;
              objChildrens.menuId=data[i].menuId;
              objChildrens.parentId=data[i].parentId;
              objChildrens.children = [];
              childrenArr.push(objChildrens);
            }
          }
          //二级菜单装入一级菜单
          var lever2Arr = [];
          for(var i in parentData) {
            for(var j in childrenArr) {
              if(parentData[i].menuId === childrenArr[j].parentId) {
                parentData[i].children.push(childrenArr[j]);
                lever2Arr.push(childrenArr[j])
              }
            }
          }
          getTreeChildren(parentData,childrenArr,lever2Arr);

        }
        function getTreeChildren(parentData,childrenArr,lever2Arr) {
          //找到三级菜单
          var lever3Arr = [];
          for(var i in childrenArr) {
            for(var j in lever2Arr) {
              if(lever2Arr[j].menuId === childrenArr[i].parentId) {
                lever3Arr.push(childrenArr[i])
              }
            }
          }
          //三级放入
          for(var i in lever3Arr) {
            for(var j in parentData) {
              for(var k in parentData[j].children) {
                if(parentData[j].children[k].menuId === lever3Arr[i].parentId) {
                  parentData[j].children[k].children.push(lever3Arr[i]);
                  getTreeChildren(parentData[j].children,childrenArr,lever3Arr);
                }
              }
            }
          }


        }

        Menu.getMenuList().then(data => {
          //console.log('获得的tree数据',data);
          getTree(data,this.menuData);
          console.log('整理后的tree数据',this.menuData);
        })
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      changePage(p) {
        this.fetchData(p)
      },
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.pageSize = val;
        this.currentPage = 1;
        this.fetchData(1);

      },
    },
    computed: {
      tableHeight() {
        const filterHeight = 28
        var tableHeight = this.getTableHeight(filterHeight)
        return tableHeight;
      },
      routes() {
        return this.$router.options.routes
      }
    }
  }
</script>
